import { Image, RichText, ScrollView, Text, Textarea, View, Progress } from '@tarojs/components';
import { eventCenter, getCurrentInstance } from "@tarojs/runtime";
import Taro from "@tarojs/taro";
import classNames from 'classnames';
import { useEffect, useState } from "react";
import data from '../../util/data';
import CustomSocket from '../../util/socket';
import createTimer from '../../util/time';
import './index.less';
import { createImgMessage, createMessage, createMjRequest, createMjSubmitChangeRequest, MJApiPath, MJSubmitResp, paintDefaultMessage, PaintMessage } from './msg';
import { WorkItem } from '../work-detail/msg';

let socket = new CustomSocket('wss://wx.axises.fun')
// let socket = new CustomSocket('ws://localhost:80')
const robot = require('../../assert/Paint_Icon_Robot.png')
const person = require('../../assert/Paint_Icon_Robot_2.png')
const sendButtonImg = require('../../assert/Paint_Icon_Send.png')
const placeholderImg = require('../../assert/Img_Line.png')
const loadingImg = require('../../assert/Paint_Icon_Loading.png')

let timer = createTimer(3 * 60 * 1000)

const PaintChat = ({ tabBarHeight = 60 }) => {
	const [historyMsgList, setHistoryMsgList] = useState<PaintMessage[]>([]);
	const [messageContent, setMessageContent] = useState('');
	const [lastMessageContent, setLastMessageContent] = useState('');
	const [scrollHeight, setScrollHeight] = useState('100vh');
	const [inputBottom, setInputBottom] = useState(0);
	const [listScrollTop, setListScrollTop] = useState(14999);
	const [moveTime, setMoveTime] = useState(1);
	const [isLoading, setIsLoading] = useState(false);
	const [isImgLoading, setIsImgLoading] = useState(false);
	const [progess, setProgress] = useState(0);
	const [textAreaHeight, setTextAreaHeight] = useState(40);

	const onReady = () => {
		loadHistoryMsgList();
		setIsLoading(false);

		// timer.onTimeout(() => {
		// 	console.log('检测 timeout');	
		// })
		// timer.start();
	}
	const onShow = () => {
		console.log('on paint chat show...');
		socket.onSocketMessage(updateMessage);
		if (data.pageShareInfo.makeSamePrompt !== '') {
			setMessageContent(data.pageShareInfo.makeSamePrompt)
			data.pageShareInfo.makeSamePrompt = ''
		}

		// if (isLoading) { // loading时检查任务
		// 	socket.sendMjMessage(createMjRequest(MJApiPath.TASK_TRACE, 'taskId'));
		// }
	}

	useEffect(() => {
		// 注册一个事件处理函数，当页面Ready时调用onReady函数
		const onReadyEventId = getCurrentInstance().router?.onReady
		eventCenter.on(onReadyEventId ? onReadyEventId : "空ID", onReady, this)
		const onShowEventId = getCurrentInstance().router?.onShow
		eventCenter.on(onShowEventId ? onShowEventId : "空ID", onShow, this)

		// 如果socket已经连接并打开，直接返回
		if (socket && socket.socketOpen) {
			console.log('socket已经连接并打开')
			return
		}

		// 组件卸载时执行
		return () => {
			// 清空消息列表
			setHistoryMsgList([])
			// 重置加载状态
			setIsLoading(false)
		}
	}, [])


	const updateMessage = (msg: string) => {
		console.log('收到消息：', msg)
		let msgResp = JSON.parse(msg) as MJSubmitResp
		switch (msgResp.code) {
			case -1:
			case -2:
			case -3:
				exceptionMsgHandle(msgResp)
				return;
			case 1000: // 提交成功，保存任务信息
				console.log('任务提交成功的消息响应: ', msg)
				updateItemInfo(msgResp)
			case 1001: // 进度更新
				updateImageResult(msgResp)
			case 1200: // 更新图片结果
				updateImageResult(msgResp)
				return
		}

		console.log('检测loading状态: ', isLoading)
		// 如果不是任务处理中，则不处理内容类型的消息
		// if (!isLoading) {
		// 	console.log('非任务监听中，不处理内容', msg)
		// 	return
		// }

		updateScrollTop()
	}

	const exceptionMsgHandle = (msgResp: MJSubmitResp) => {
		setHistoryMsgList(historyMsgList => {
			if (historyMsgList.length === 0) return historyMsgList
			// 找到最后一个占位消息，替换为正式消息数据
			let prevElement = historyMsgList[historyMsgList.length - 1]
			prevElement.content = msgResp.errMsg
			prevElement.image = ''
			historyMsgList = historyMsgList.slice(0, historyMsgList.length - 1).concat(prevElement)
			return historyMsgList
		});
		setIsLoading(false)
	}

	const updateItemInfo = (msgResp: MJSubmitResp) => {
		setHistoryMsgList(historyMsgList => {
			if (historyMsgList.length === 0) return historyMsgList
			// 找到最后一个占位消息，替换为正式消息数据
			let prevElement = historyMsgList[historyMsgList.length - 1]
			if (msgResp.taskId !== '') {
				prevElement.taskId = msgResp.taskId
			}
			historyMsgList = historyMsgList.slice(0, historyMsgList.length - 1).concat(prevElement)
			return historyMsgList
		});
	}

	const updateImageResult = (msgResp: MJSubmitResp) => {
		setProgress(msgResp.progress)
		if (msgResp.code === 1200) {
			setIsLoading(false);
		}
		setHistoryMsgList(historyMsgList => {
			if (historyMsgList.length === 0) return historyMsgList
			// 找到最后一个占位消息，替换为正式消息数据
			let prevElement = historyMsgList[historyMsgList.length - 1]
			if (msgResp.imageUrl !== '') {
				prevElement.content = ''
				prevElement.image = msgResp.imageUrl
				prevElement.imageProgess = msgResp.progress
				saveHistoryMsgList()
			}
			historyMsgList = historyMsgList.slice(0, historyMsgList.length - 1).concat(prevElement)
			return historyMsgList
		});
	}

	const handleMessageSubmit = (isRefresh: boolean) => {
		if (!isRefresh && messageContent && messageContent.trim() !== '') {
			setLastMessageContent(messageContent.trim())
		}
		setLastMessageContent(lastMsgContent => {
			if (lastMsgContent && lastMsgContent.trim() !== '') {
				let message = createMessage(lastMsgContent.trim(), 'user');
				console.log('当前消息：', message);

				setHistoryMsgList((prev) => prev.concat(message));

				setIsLoading(true);
				setIsImgLoading(false)
				setMoveTime(moveTime + 1);

				// 清空输入的消息内容
				setMessageContent('');
				updateScrollTop()

				// 先添加占位一个空消息，等待服务端响应
				setHistoryMsgList(prev => prev.concat(createImgMessage('placeholder', lastMsgContent.trim())));
				startTimeoutListen()

				socket.sendMjMessage(createMjRequest(MJApiPath.SUBMIT, message.content));
				// test mock
				// const jsonStr = '{"code": 0, "state": "", "progress": 24, "imageUrl": "http://ys-aigc.oss-cn-beijing.aliyuncs.com/mj/KVYOJU.png?x-oss-process=image/crop,w_1024,y_1024,g_nw"}';
				// updateMessage(jsonStr);

			}
			return lastMsgContent;
		})

	}

	const startTimeoutListen = () => {
		setIsLoading(prev => {
			setTimeout(() => {
				console.log('发消息后超时监听')
				if (prev) {
					setIsLoading(false);
				}
			}, 5 * 60 * 1000)
			return prev
		})
	}

	const saveHistoryMsgList = () => {
		setHistoryMsgList(prev => {
			Taro.setStorage({
				key: 'historyMsgList',
				data: prev,
				success: function () {
					console.log('数据存储成功');
				},
				fail: function () {
					console.log('数据存储失败');
				}
			})
			return prev;
		})
	}

	const loadHistoryMsgList = () => {
		setHistoryMsgList(prev => {
			let localRecord = Taro.getStorageSync('historyMsgList') as PaintMessage[];
			console.log('本地缓存的历史消息列表：', localRecord);
			if (localRecord) { // 检查一次云端是否成功了
				// localRecord.map((item) => {
				// 	if (item) {

				// 	}
				// })
				return localRecord;
			}
			return prev.concat(paintDefaultMessage);
		})
		// updateScrollTop()
		setListScrollTop(1400)
	}

	const updateScrollTop = () => {
		// setScrollHeight('1000px')
		setListScrollTop(prev => {
			prev = (listScrollTop + (historyMsgList.length + 1) * 1000 + moveTime * 10000)
			return prev
		});
	}

	const handleLineChange = (event) => {
		setTextAreaHeight(event.detail.height)
	}

	const handleKeyboardHeightChange = (e) => {
		setInputBottom(e.detail.height === 0 ? e.detail.height : e.detail.height - tabBarHeight - 25);
	}

	const handleFocus = (e) => {
		// setAddMediaModal(false);
		setInputBottom(e.detail.height === 0 ? e.detail.height : e.detail.height - tabBarHeight - 25);
	}

	const handleBlur = () => {
		const scrollHeight = '100vh';
		setScrollHeight(scrollHeight);
		setInputBottom(0);
	}

	const handleInput = (e) => {
		setMessageContent(e.detail.value);
	}

	const isRobot = item => {
		return item.type === 'robot';
	}

	const formatMessages = () => {
		return historyMsgList.length > 0 ? historyMsgList : [paintDefaultMessage];
	}

	const refreshGenerate = () => {
		if (historyMsgList.length > 2) {
			setLastMessageContent(historyMsgList[historyMsgList.length - 2].content);
		}
		handleMessageSubmit(true)
	}

	const btnU = (item: PaintMessage, idx: number) => {
		// http://ys-aigc.oss-cn-beijing.aliyuncs.com/mj/ucun6B.jpg?x-oss-process=image/resize,w_512/quality,q_50
		// item.image.split("?")[0]
		let newImageUrl = ''
		switch (idx) {
			case 1:
				console.log('左上放大')
				newImageUrl = item.image + "/crop,w_256,h_256,y_0,g_nw"
				break
			case 2:
				console.log('右上放大')
				newImageUrl = item.image + "/crop,w_256,h_256,x_256,g_nw"
				break
			case 3:
				console.log('左下放大')
				newImageUrl = item.image + "/crop,w_256,h_256,y_256,g_nw"
				break
			case 4:
				console.log('右下放大')
				newImageUrl = item.image + "/crop,w_256,h_256,x_256,y_256,g_nw"
				break
		}
		console.log("U选择后的图片url：", newImageUrl)
		let message = createImgMessage(newImageUrl, item.prompt)
		message.imageType = idx
		setHistoryMsgList((prev) => prev.concat(message))
		saveHistoryMsgList()
		startTimeoutListen()
	}

	const btnV = (item: PaintMessage, idx: number) => {
		// http://ys-aigc.oss-cn-beijing.aliyuncs.com/mj/ucun6B.jpg?x-oss-process=image/resize,w_512/quality,q_50
		// item.image.split("?")[0]

		console.log("V选择的idx：", idx, "之前的任务信息：", item.taskId)

		setIsLoading(true);
		setIsImgLoading(false)
		setMoveTime(moveTime + 1)
		updateScrollTop()
		// 先添加占位一个空消息，等待服务端响应
		setHistoryMsgList(prev => prev.concat(createImgMessage('placeholder', item.prompt)));

		socket.sendMjMessage(createMjSubmitChangeRequest(item.taskId, idx));
	}

	const handleWorkClick = (item: PaintMessage) => {
		let workItem: WorkItem = {
			id: 0,
			prompt: item.prompt,
			taskId: item.taskId,
			imageUrl: item.image,
			createTime: item.createTime,
		}
		Taro.navigateTo({
			url: `/pages/common/work-detail/index?workItem=${encodeURIComponent(JSON.stringify(workItem))}&imageType=${item.imageType}`,
		})
	}

	const renderImageContent = (item: PaintMessage) => {
		return (
			<View style={{ width: '100%' }}>
				<Progress percent={item.imageProgess} active={item.imageProgess < 100} activeMode='forwards' borderRadius='2' strokeWidth='4' fontSize={10} style={{ display: 'flex', width: '100%', margin: '2px 0' }} />
				<View style={{ display: 'flex', flexDirection: 'row', width: '100%', justifyContent: 'flex-start', alignItems: 'flex-end' }}>
					<Image src={item.image} mode='widthFix' style={{ width: '100%', height: 'auto', borderRadius: '2px' }} onLoad={() => setIsImgLoading(true)} onClick={() => handleWorkClick(item)} />
					{/* {isImgLoading && (
						
					)} */}
				</View>
				{/* {console.log('进度：', item.imageProgess)} */}
				{
					(item.imageType === 0 || item.imageType === undefined) && item.imageProgess >= 98 && isImgLoading && (
						<View style={{ display: 'flex', width: '100%', margin: '0px 0', alignItems: 'flex-start', justifyContent: '', flexDirection: 'column' }}>
							<View style={{ display: 'flex', width: '100%', margin: '5px 0', alignItems: 'center', justifyContent: 'space-between' }}>
								<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 1)} style={{ fontSize: '10px', color: '#ffffff' }}>左上放大</Text></View>
								<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 2)} style={{ fontSize: '10px', color: '#ffffff' }}>右上放大</Text></View>
								<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 3)} style={{ fontSize: '10px', color: '#ffffff' }}>左下放大</Text></View>
								<View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => btnU(item, 4)} style={{ fontSize: '10px', color: '#ffffff' }}>右下放大</Text></View>
								{/* <View className="btn_UV" style={{ marginRight: '0px' }}><Image src={loadingImg} onClick={refreshGenerate} mode="aspectFill" style={{ width: '10px', height: '10px' }} /></View> */}

							</View>
							<View style={{ display: 'flex', width: '100%', margin: '0px 0', alignItems: 'center', justifyContent: 'space-between' }}>
								<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnV(item, 1)} style={{ fontSize: '10px', color: '#ffffff' }}>左上相似</Text></View>
								<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnV(item, 2)} style={{ fontSize: '10px', color: '#ffffff' }}>右上相似</Text></View>
								<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnV(item, 3)} style={{ fontSize: '10px', color: '#ffffff' }}>左下相似</Text></View>
								<View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => btnV(item, 4)} style={{ fontSize: '10px', color: '#ffffff' }}>右下相似</Text></View>
								{/* <View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => btnU(item, 1)} style={{ fontSize: '10px', color: '#ffffff' }}>高清修复</Text></View> */}
							</View>
						</View>
					)}
				{/* {(item.imageType === 1) && isImgLoading && (
					<View style={{ display: 'flex', width: '100%', margin: '0px 0', alignItems: 'flex-start', justifyContent: '', flexDirection: 'column' }}>
						<View style={{ display: 'flex', width: '100%', margin: '5px 0', alignItems: 'center', justifyContent: 'space-between' }}>
							<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => btnU(item, 1)} style={{ fontSize: '10px', color: '#ffffff' }}>高清修复 2x</Text></View>
							<View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => btnU(item, 2)} style={{ fontSize: '10px', color: '#ffffff' }}>高清修复 4x</Text></View>
						</View>
						<View style={{ display: 'flex', width: '100%', margin: '0px 0', alignItems: 'center', justifyContent: 'space-between' }}>
							<View className="btn_UV" style={{ marginRight: '5px' }}><Text onClick={() => console.log('左上相似')} style={{ fontSize: '10px', color: '#ffffff' }}>高清修复 8x</Text></View>
							<View className="btn_UV" style={{ marginRight: '0px' }}><Text onClick={() => console.log('右上相似')} style={{ fontSize: '10px', color: '#ffffff' }}>高清修复 10x</Text></View>
						</View>
					</View>
				)} */}
			</View>
		)
	}

	const renderProgress = (item: PaintMessage) => {
		return (
			<View style={{ position: 'relative', width: '100%' }}>
				<Image src={placeholderImg} mode="widthFix" style={{ width: '100%', height: 'auto' }} />
				{isLoading && (
					<View style={{ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
						<View style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
							<Image src={loadingImg} mode="aspectFill" style={{ width: '20px', height: '20px', animation: 'rotate 3s linear infinite' }} />
							<Text>{`生成中(${item.imageProgess}%)`}</Text>
						</View>
					</View>
				)}
			</View>
		)
	}

	return (
		<View className='im-page'>
			<View>
				<ScrollView className='paint-container' style={{ height: scrollHeight }} enableFlex enableBackToTop scrollY scrollTop={listScrollTop}>
					{formatMessages().map((item) => {
						return (
							<View key={item.id} className={classNames({ 'im-list--item__robot': isRobot(item), 'im-list--item': true })}>
								<Image className="list-item--avatar" src={isRobot(item) ? robot : person} mode="aspectFill" lazyLoad />
								<View style={{ width: '100%' }}>
									<View className="list-item--name">{isRobot(item) ? "绘画助理" : "HuanJing"}</View>
									{item.image ?
										(
											item.image.startsWith('http') ? renderImageContent(item) : renderProgress(item)
										) :
										(<View className="list-item--content"><RichText nodes={item.content} /></View>)}
								</View>
							</View>
						);
					})}
					<View className='placeholder-box' />
				</ScrollView>
			</View>
			<View className='im-toolbar' style={{ bottom: inputBottom }}>
				<Textarea
					style={{ height: `${textAreaHeight}px`, marginLeft: '10px', paddingLeft: '10px', fontSize: '13px', verticalAlign: 'center', border: '0px', backgroundColor: '#242328' }}
					placeholder={isLoading ? '正在生成...' : '请输入你想要的画面描述'}
					placeholderStyle='color: #cccccc;'
					showConfirmBar={false}
					maxlength={1000}
					disabled={isLoading}
					value={messageContent}
					adjustPosition={true}
					adjust-keyboard-to='false'
					disableDefaultPadding={false}
					confirmType='send'
					onKeyboardHeightChange={handleKeyboardHeightChange}
					onFocus={handleFocus}
					onBlur={handleBlur}
					onInput={handleInput}
					onConfirm={() => handleMessageSubmit(false)}
					onLineChange={handleLineChange}
				/>
				<View className="send-button" onClick={() => handleMessageSubmit(false)}>
					<Image src={sendButtonImg} mode="aspectFit" style={{ width: '25px', height: '25px' }} />
				</View>
			</View>

		</View>
	);
}

export default PaintChat
